package cn.gok.springsecuritydemo05.handler;

import cn.gok.springsecuritydemo05.util.JWTUtil;
import cn.gok.springsecuritydemo05.util.ResultData;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
    登录成功后的提示，并产生JWT Token 返回给前端
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    JWTUtil jwtUtil;


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {

        //1、取出用户的信息
        UserDetails userDetails = (UserDetails)authentication.getPrincipal();
        String username = userDetails.getUsername();

        Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
        String[] roles = new String[authorities.size()];
        int i = 0;
        for (GrantedAuthority authority : authorities) {
            roles[i] = authority.getAuthority();
            i++;
        }

        Map<String, Object> payload = new HashMap<>();
        payload.put("username",username);
        payload.put("roles",roles);

        //2、产生jwt token
        String token = jwtUtil.createToken(payload);

        //3、响应给前端
        response.setContentType("application/json;charset=utf8");
        ResultData resultData = ResultData.createData(200, "登录成功", token);
        response.getWriter().write(JSONUtil.toJsonStr(resultData));

    }
}
